package cn.sfrog.project.biz.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.sfrog.common.constant.Constants;
import cn.sfrog.common.exception.ApiException;
import cn.sfrog.common.utils.DateUtils;
import cn.sfrog.common.utils.SecurityUtils;
import cn.sfrog.common.utils.StringUtils;
import cn.sfrog.project.biz.admin.domain.BizCombo;
import cn.sfrog.project.biz.admin.domain.BizHospital;
import cn.sfrog.project.biz.admin.domain.BizSearchKeyword;
import cn.sfrog.project.biz.admin.domain.BizService;
import cn.sfrog.project.biz.admin.domain.vo.BizHospitalFormVO;
import cn.sfrog.project.biz.admin.domain.vo.BizHospitalQueryVO;
import cn.sfrog.project.biz.admin.domain.vo.BizHospitalVO;
import cn.sfrog.project.biz.admin.mapper.BizDoctorMapper;
import cn.sfrog.project.biz.admin.mapper.BizHospitalMapper;
import cn.sfrog.project.biz.admin.service.*;
import cn.sfrog.project.biz.applet.utils.PinyinUtil;
import cn.sfrog.project.biz.web.vo.index.*;
import cn.sfrog.project.biz.web.vo.order.AppServiceHospitalResultVO;
import cn.sfrog.project.biz.web.vo.service.AppServiceDetailQueryVO;
import cn.sfrog.system.domain.vo.BizStatusChangeVO;
import cn.sfrog.system.domain.vo.app.AppEscortQueryVO;
import cn.sfrog.system.domain.vo.app.AppEscortResultVO;
import cn.sfrog.system.domain.vo.app.AppServiceQueryVO;
import cn.sfrog.system.domain.vo.app.AppServiceResultVO;
import cn.sfrog.system.service.ISysUserService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 医院Service业务层处理
 */
@Service
public class BizHospitalServiceImpl extends ServiceImpl<BizHospitalMapper, BizHospital> implements IBizHospitalService {
    @Autowired
    private BizDoctorMapper bizDoctorMapper;
    @Resource
    private BizHospitalMapper bizHospitalMapper;
    @Autowired
    private IBizDepartmentService bizDepartmentService;
    @Autowired
    private IBizDoctorService bizDoctorService;
    @Autowired
    private IBizServiceService bizServiceService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IBizSearchKeywordUserHistoryService bizSearchKeywordUserHistoryService;

    /**
     * 查询医院
     *
     * @param id 医院主键
     * @return 医院
     */
    @Override
    public BizHospitalVO selectBizHospitalById(Long id) {
        BizHospitalVO bizHospitalVO = bizHospitalMapper.selectBizHospitalById(id);

        if(StringUtils.isNotBlank(bizHospitalVO.getImages())){
            List<String> imageList = JSONObject.parseArray(bizHospitalVO.getImages(), String.class);
            bizHospitalVO.setImageList(imageList);
        }
        return bizHospitalVO;
    }

    /**
     * 查询医院列表
     *
     * @param query 医院
     * @return 医院
     */
    @Override
    public List<BizHospitalVO> selectBizHospitalList(BizHospitalQueryVO query) {
        return bizHospitalMapper.selectBizHospitalList(query);
    }

    /**
     * 新增医院
     *
     * @param form 医院
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean insertBizHospital(BizHospitalFormVO form) {
        BizHospital bizHospital = new BizHospital();
        LambdaQueryWrapper<BizHospital> lambdaQueryWrapper = new LambdaQueryWrapper<BizHospital>()
                .eq(BizHospital::getName,form.getName());
        BizHospital hospital = BizHospital.DAO.selectOne(lambdaQueryWrapper);
        if(StringUtils.isNotNull(hospital)){
            throw new ApiException("该医院名称已存在");
        }
        BeanUtils.copyProperties(form, bizHospital);
        if(form.getImageArr() != null){
            bizHospital.setImages(JSONObject.toJSONString(form.getImageArr()));
        }
        bizHospital.setCreateTime(new Date());
        bizHospital.setCreateBy(SecurityUtils.getUsername());
        bizHospital.setUpdateTime(new Date());
        bizHospital.setUpdateBy(SecurityUtils.getUsername());
        return bizHospital.insert();
    }

    /**
     * 修改医院
     *
     * @param form 医院
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean updateBizHospital(BizHospitalFormVO form) {
        BizHospital hospital = BizHospital.DAO.selectById(form.getId());
        if(hospital != null){
            LambdaQueryWrapper<BizHospital> lambdaQueryWrapper = new LambdaQueryWrapper<BizHospital>()
                    .eq(BizHospital::getName,form.getName())
                    .ne(BizHospital::getId,hospital.getId());
            BizHospital dbHospital = BizHospital.DAO.selectOne(lambdaQueryWrapper);
            if(StringUtils.isNotNull(dbHospital)){
                throw new ApiException("该医院名称已存在");
            }
        }
        BizHospital bizHospital = new BizHospital();
        BeanUtils.copyProperties(form, bizHospital);
        if(form.getImageArr() != null){
            bizHospital.setImages(JSONObject.toJSONString(form.getImageArr()));
        }
        bizHospital.setUpdateTime(new Date());
        bizHospital.setUpdateBy(SecurityUtils.getUsername());
        return bizHospital.updateById();
    }

    /**
     * 批量删除医院
     *
     * @param ids 需要删除的医院主键
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean deleteBizHospitalByIds(Long[] ids) {
            return BizHospital.DAO.delete(Wrappers.lambdaQuery(BizHospital.class).in(BizHospital::getId, (Object[]) ids));
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean changeStatus(BizStatusChangeVO vo) {
        return BizHospital.DAO.update(Wrappers.lambdaUpdate(BizHospital.class).in(BizHospital::getId, (Object[]) vo.getIds()).set(BizHospital::getStatus, vo.getStatus()));
    }

    @Override
    public List<AppHospitalResultVO> selectAppIndexHospitalList(AppHospitalQueryVO queryVO) {
        return bizHospitalMapper.selectAppIndexHospitalList(queryVO);
    }

    @Override
    public List<AppHospitalResultVO> selectAllHospitalList(AppHospitalQueryVO queryVO) {
        return bizHospitalMapper.selectAllHospitalList(queryVO);
    }

    @Override
    public AppHospitalDetailResultVO selectAppHospitalDetail(Long id) {
        AppHospitalDetailResultVO resultVO = bizHospitalMapper.selectAppHospitalDetail(id);
        if(StringUtils.isNotNull(resultVO)){
            if(StringUtils.isNotBlank(resultVO.getImages())){
                List<String> imageList = JSONObject.parseArray(resultVO.getImages(), String.class);
                resultVO.setImageList(imageList);
            }
            //查询医院下的科室
            List<AppDepartmentResultVO> departmentResultVOList = bizDepartmentService.selectAppDepartmentListByHospitalId(id);
            for (int i = 0; i < departmentResultVOList.size(); i++) {
                String pinyin = PinyinUtil.getPinyin(departmentResultVOList.get(i).getDepartmentName());
                departmentResultVOList.get(i).setDepartmentNameByPy(pinyin);
            }
            resultVO.setDepartmentList(departmentResultVOList);
        }

        return resultVO;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public AppGlobalSearchVO selectAppIndexGlobalSearch(String keyword,String cityCode,String type) {
        AppGlobalSearchVO appGlobalSearchVO = new AppGlobalSearchVO();
        AppHospitalQueryVO hospitalQueryVO = new AppHospitalQueryVO();
        AppDoctorQueryVO doctorQueryVO = new AppDoctorQueryVO();
        AppServiceQueryVO serviceQueryVO = new AppServiceQueryVO();
        AppEscortQueryVO escortQueryVO = new AppEscortQueryVO();
        hospitalQueryVO.setCityCode(cityCode);
//        hospitalQueryVO.setPageNum(pageNum);
//        hospitalQueryVO.setPageSize(pageSize);
        doctorQueryVO.setCityCode(cityCode);
//        doctorQueryVO.setPageNum(pageNum);
//        doctorQueryVO.setPageSize(pageSize);
        escortQueryVO.setCityCode(cityCode);
//        escortQueryVO.setPageNum(pageNum);
//        escortQueryVO.setPageSize(pageSize);
        serviceQueryVO.setCityCode(cityCode);
        hospitalQueryVO.setName(keyword);
        doctorQueryVO.setDoctorName(keyword);
        serviceQueryVO.setName(keyword);
        escortQueryVO.setNickName(keyword);
        if("1".equals(type)){
            //查询名院
            List<AppHospitalResultVO> hospitalResultVOList = bizHospitalMapper.selectAllHospitalList(hospitalQueryVO);
            //查询名医
            List<AppDoctorDetailResultVO> doctorList = bizDoctorService.selectAppFamousDoctorList(doctorQueryVO);
            //查询陪护(包括陪诊和护工)
            List<AppEscortResultVO> escortList =  sysUserService.selectAppEscortList(escortQueryVO);
            //查询服务
            List<AppServiceResultVO> serviceList = bizServiceService.selectAppServiceList2(serviceQueryVO);
            appGlobalSearchVO.setHospitalList(hospitalResultVOList);
            appGlobalSearchVO.setHospitalCount(CollectionUtil.isNotEmpty(hospitalResultVOList) ? hospitalResultVOList.size() : 0);
            appGlobalSearchVO.setDoctorCount(CollectionUtil.isNotEmpty(doctorList) ? doctorList.size() : 0);
            appGlobalSearchVO.setEscortCount(CollectionUtil.isNotEmpty(escortList) ? escortList.size() : 0);
            appGlobalSearchVO.setServiceCount(CollectionUtil.isNotEmpty(serviceList) ? serviceList.size() : 0);
        }else if("2".equals(type)){
            //查询名医

            List<AppDoctorDetailResultVO> doctorList = bizDoctorService.selectAppFamousDoctorList(doctorQueryVO);

            //查询名院
            List<AppHospitalResultVO> hospitalResultVOList = bizHospitalMapper.selectAllHospitalList(hospitalQueryVO);

            //查询陪护(包括陪诊和护工)
            List<AppEscortResultVO> escortList =  sysUserService.selectAppEscortList(escortQueryVO);
            //查询服务
            List<AppServiceResultVO> serviceList = bizServiceService.selectAppServiceList2(serviceQueryVO);

            appGlobalSearchVO.setHospitalCount(CollectionUtil.isNotEmpty(hospitalResultVOList) ? hospitalResultVOList.size() : 0);
            appGlobalSearchVO.setDoctorList(doctorList);
            appGlobalSearchVO.setDoctorCount(CollectionUtil.isNotEmpty(doctorList) ? doctorList.size() : 0);
            appGlobalSearchVO.setEscortCount(CollectionUtil.isNotEmpty(escortList) ? escortList.size() : 0);
            appGlobalSearchVO.setServiceCount(CollectionUtil.isNotEmpty(serviceList) ? serviceList.size() : 0);

        }else if("3".equals(type)){
            //查询陪护(包括陪诊和护工)
            List<AppEscortResultVO> escortList =  sysUserService.selectAppEscortList(escortQueryVO);
            //查询名医
            List<AppDoctorDetailResultVO> doctorList = bizDoctorService.selectAppFamousDoctorList(doctorQueryVO);

            //查询名院
            List<AppHospitalResultVO> hospitalResultVOList = bizHospitalMapper.selectAllHospitalList(hospitalQueryVO);

            //查询服务
            List<AppServiceResultVO> serviceList = bizServiceService.selectAppServiceList2(serviceQueryVO);
            appGlobalSearchVO.setHospitalCount(CollectionUtil.isNotEmpty(hospitalResultVOList) ? hospitalResultVOList.size() : 0);
            appGlobalSearchVO.setDoctorCount(CollectionUtil.isNotEmpty(doctorList) ? doctorList.size() : 0);
            appGlobalSearchVO.setEscortList(escortList);
            appGlobalSearchVO.setEscortCount(CollectionUtil.isNotEmpty(escortList) ? escortList.size() : 0);
            appGlobalSearchVO.setServiceCount(CollectionUtil.isNotEmpty(serviceList) ? serviceList.size() : 0);
        }else if("4".equals(type)){
            //查询服务
            List<AppServiceResultVO> serviceList = bizServiceService.selectAppServiceList2(serviceQueryVO);
            //查询陪护(包括陪诊和护工)
            List<AppEscortResultVO> escortList =  sysUserService.selectAppEscortList(escortQueryVO);
            //查询名医
            List<AppDoctorDetailResultVO> doctorList = bizDoctorService.selectAppFamousDoctorList(doctorQueryVO);

            //查询名院
            List<AppHospitalResultVO> hospitalResultVOList = bizHospitalMapper.selectAllHospitalList(hospitalQueryVO);

            appGlobalSearchVO.setHospitalCount(CollectionUtil.isNotEmpty(hospitalResultVOList) ? hospitalResultVOList.size() : 0);
            appGlobalSearchVO.setDoctorCount(CollectionUtil.isNotEmpty(doctorList) ? doctorList.size() : 0);
            appGlobalSearchVO.setEscortCount(CollectionUtil.isNotEmpty(escortList) ? escortList.size() : 0);
            appGlobalSearchVO.setServiceList(serviceList);
            appGlobalSearchVO.setServiceCount(CollectionUtil.isNotEmpty(serviceList) ? serviceList.size() : 0);
        }
        if(StringUtils.isNotBlank(keyword)){
            //记录搜索关键字
            Boolean isUpdate = false;
            LambdaQueryWrapper<BizSearchKeyword> queryWrapper = new LambdaQueryWrapper<BizSearchKeyword>()
                    .eq(BizSearchKeyword::getKeyword,keyword);
            BizSearchKeyword dbSearchKeyword = BizSearchKeyword.DAO.selectOne(queryWrapper);
            BizSearchKeyword searchKeyword = new BizSearchKeyword();
            if(StringUtils.isNull(dbSearchKeyword)){
                searchKeyword.setKeyword(keyword);
                searchKeyword.setSearchCount(1);
                searchKeyword.insert();
            }else {
                isUpdate = true;
                dbSearchKeyword.setSearchCount(dbSearchKeyword.getSearchCount() + 1);
                dbSearchKeyword.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
                dbSearchKeyword.setUpdateTime(DateUtils.getNowDate());
                dbSearchKeyword.updateById();
            }
            //记录用户搜索历史
            bizSearchKeywordUserHistoryService.insertOrUpdateSearchHistory(isUpdate,isUpdate ? dbSearchKeyword.getId() : searchKeyword.getId());
        }

        return appGlobalSearchVO;
    }

    @Override
    public List<AppServiceHospitalResultVO> selectAppServiceHospitalList(AppServiceDetailQueryVO queryVO) {
        List<AppServiceHospitalResultVO> hospitalList = new ArrayList<>();
        String hospitalIds = null;
        if(Constants.TYPE_SERVICE.equals(queryVO.getType())){
            //服务
            hospitalIds =  BizService.DAO.selectById(queryVO.getId()).getHospitalIds();
        }else if(Constants.TYPE_COMBO.equals(queryVO.getType())){
            //套餐
            hospitalIds = BizCombo.DAO.selectById(queryVO.getId()).getHospitalIds();
        }
        if(StringUtils.isNotBlank(hospitalIds)){
            String[] ids = hospitalIds.split(",");
            if(ids.length > 0){
                hospitalList = bizHospitalMapper.selectAppServiceHospitalList(ids);
            }
        }
        return hospitalList;
    }

    @Override
    public List<AppHospitalVO> selectAppAllHospitalList() {
        return bizHospitalMapper.selectAppAllHospitalList();
    }
}
